import {Table, Menu, Dropdown, Icon, message, Button} from 'antd';
// import Table from '../../../_antd1.11.2/table'
// import Menu from '../../../_antd1.11.2/menu'
// import Dropdown from '../../../_antd1.11.2/dropdown'
// import Icon from '../../../_antd1.11.2/icon'
// import message from '../../../_antd1.11.2/message'
// import Button from '../../../_antd1.11.2/Button'
import cloneDeep from 'lodash/cloneDeep'
import WeaTools from '../../wea-tools';
const MenuItem = Menu.Item;
import isEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray';
import isEqual from 'lodash/isEqual'

//weaSimple:简单分页
//scroll : 启用内部滚动 false(默认)
//heightSpace : 启用内部滚动后高度调整 Number
//usePagination : 是否开启 table分页  true(默认)
//size : 正常或迷你类型，default(默认)、 small
//useFixedHeader : 是否固定表头 false(默认)
//bordered : 是否展示外边框和列边框 false(默认)
//showHeader : 是否显示表头 true(默认)
//useFilters : 使用过滤 false(默认)
//useSorter : 使用排序 true(默认)
//showCheck : 是否展示复选 默认 false(默认)
//checkType : checkbox(默认) OR radio
//noOperate : 不增加操作行 false(默认)
//refreshDatas : 是否触发table 接口 false(默认) 第一次触发之前,需要先传入一次datakey,每次触发接口需 false->true
//useLoading : 是否开启table 自身loading false(默认)
//---------pagination----------
//showSizeChanger : 显示分页大小选择 true(默认)
//showQuickJumper : 显示快速跳转 true(默认)
//showTotal : 显示总数量 true(默认)
//---------function----------
//onChange(pagination,filter,sorter) : 获取table操作 分页、排序、本地过滤、信息 (obj,obj,obj)
//getSelection(selectedRowKeys) : 获取选中行信息 (string)
//getTableLoading(bool) : 获取table 加载状态 (bool)
//onRowClick(record,index) : 行点击事件 (obj,number)

//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	customColTitle: '定制列',
  	customColSelect: '待选列名',
  	customColSelected: '已选列名',
  	customColSave: '保存',
  	customColCancel: '取消',
};

class Main extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTable;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
	constructor(props) {
		super(props);
        let columns = [];
        let datas = [];
        let selectedRowKeys = [];
        if (props.noSkHasPgTable) {
            columns = props.noSkHasPgTable.hasPgTableData.columns || [];
            datas = props.noSkHasPgTable.hasPgTableData.datas || [];
        }
        if (!isEmpty(props.noPgTableData)) {
            columns = props.noPgTableData.columns || [];
            datas = props.noPgTableData.datas;
        }
        if (!isEmpty(props.checkedDatas)) {
            props.checkedDatas.forEach((d)=> {
                selectedRowKeys.push(d.id);
            });
        }
		this.state = {
			height: props.scrollHeight || 0,
			showCheck: props.showCheck || false,
			columns: columns,
			datas: datas,
			operates: [],
			sortParams: [],
			selectedRowKeys: selectedRowKeys,
			current: 1,
			count: 0,
			pageSize: props.pageSize || 20,
			loading: false,
            showCheckedDatas: false,
            checkedDatas: [],
		}
	}
	setScrollheigth() {
		const { heightSpace } = this.props;
		let hs = heightSpace || 0;
		if(jQuery(".wea-browser-table") && jQuery(".wea-browser-table .ant-pagination.ant-table-pagination")) {
			let widowClientHeight = document.documentElement.clientHeight || 0;
			let top = jQuery(".wea-browser-table").offset() ? jQuery(".wea-browser-table").offset().top : 0;
			let bottom = jQuery(".wea-browser-table .ant-pagination.ant-table-pagination").height() || 30;
			let scrollheigth = widowClientHeight - top - bottom;
			this.setState({
				height: scrollheigth - 100 - hs
			})
		}
	}
	componentDidMount() {
		// console.log('weabrowsertable:props',this.props);
		const {usePagination,noPgTableData,dataKey} = this.props;
		// console.log('noPgTableData',noPgTableData);
		usePagination && this.getTableDatas(dataKey);
		this.setScrollheigth();
		jQuery(window).resize(() => {
			this._reactInternalInstance !== undefined && this.setScrollheigth();
		});
	}
	componentWillReceiveProps(nextProps, nextState) {
		if(this.props.showCheckedDatas !== nextProps.showCheckedDatas){
            this.setState({showCheckedDatas: nextProps.showCheckedDatas})
        }
        if(this.props.dataKey !== nextProps.dataKey && !isEmpty(nextProps.dataKey)){
			this.getTableDatas(nextProps.dataKey);
		}
        if(!isEqual(this.props.noPgTableData, nextProps.noPgTableData)){
            this.setState({datas:nextProps.noPgTableData.datas, columns:nextProps.noPgTableData.columns});
        }
        if(!isEqual(this.state.checkedDatas, nextProps.checkedDatas)){
            let keys = [], datas = [];
            isArray(nextProps.checkedDatas) && nextProps.checkedDatas.forEach((d)=> {
                keys.push(d.randomFieldId || d.id);
                if (d.randomFieldId) datas.push(d);
            });
            this.setState({selectedRowKeys: keys, checkedDatas: nextProps.checkedDatas});
        }

        if (!WeaTools.isEqual(this.props.noSkHasPgTable, nextProps.noSkHasPgTable)) {
            !isEmpty(nextProps.noSkHasPgTable) && this.setState({
                current: 1,
                columns: nextProps.noSkHasPgTable.hasPgTableData.columns,
                datas: nextProps.noSkHasPgTable.hasPgTableData.datas,
                count: nextProps.noSkHasPgTable.hasPgTableData.count,
            });
        }
		// console.log('Table---componentWillReceiveProps')
	}
	// shouldComponentUpdate(nextProps,nextState) {
	// 	return this.state.height !== nextState.height ||
	// 		this.state.current !== nextState.current ||
	// 		this.state.count !== nextState.count ||
	// 		this.state.pageSize !== nextState.pageSize ||
	// 		this.state.showCheck !== nextState.showCheck ||
	// 		this.props.refreshDatas !== nextProps.refreshDatas ||
	// 		this.props.dataKey !== nextProps.dataKey ||
	// 		JSON.stringify(this.state.columns) !== JSON.stringify(nextState.columns) ||
	// 		JSON.stringify(this.state.datas) !== JSON.stringify(nextState.datas) ||
	// 		JSON.stringify(this.state.operates) !== JSON.stringify(nextState.operates) ||
	// 		JSON.stringify(this.state.selectedRowKeys) !== JSON.stringify(nextState.selectedRowKeys) ||
	// 		JSON.stringify(this.state.sortParams) !== JSON.stringify(nextState.sortParams) ||
	// 		this.props.noPgTableData !== nextProps.noPgTableData ||
	// 		this.props.noSkHasPgTable !== nextProps.noSkHasPgTable
	// }
    formatColumns(columns) {
        const { scroll, heightSpace, usePagination, size, useFixedHeader, bordered, showHeader, useFilters, useSorter, noOperate, checkType, useLoading,contentHeight } = this.props;
        const { height, datas, operates, selectedRowKeys, showCheck, loading, sortParams } = this.state;
        let newColumns = this.getColumns(columns) || [];
        let oldWidthObj = {}
        let num = 0;
        let nowWidth = 0;
        newColumns = newColumns.filter(newColumn => {
            if(newColumn.hide == "false" && newColumn.oldWidth) {
                const width = newColumn.oldWidth ? parseFloat(newColumn.oldWidth.substring(0, newColumn.oldWidth.length - 1)) : 10;
                oldWidthObj[newColumn.dataIndex] = width;
                num++;
                nowWidth += width;
            }
            return String(newColumn.hide)=='false';

        });
        !noOperate && newColumns.push({
            title: "操作",
            dataIndex: "randomFieldOperate",
            key: "randomFieldOperate",
            width: "10%",
            render(text, record, index) {
                const rfs = record.randomFieldOp ? JSON.parse(record.randomFieldOp) : {};
                let argumentString = [];
                !!record.randomFieldOpPara && record.randomFieldOpPara.map(r => { argumentString.push(r.obj) })

                let showOperate = null;
                let shouFn = null;
                let hiddenOperate = new Array();
                let opNum = 0;
                operates.map((operate, index) => {
                    let flag = operate.index || "-1";
                    if(rfs[flag] && rfs[flag] != "false") opNum++;
                    let fn = !!operate.href ? `${operate.href.split(':')[1].split(')')[0]}${record.randomFieldId},${argumentString});` : ""
                    if(rfs[flag] && rfs[flag] != "false") {
                        hiddenOperate.push(
                            <MenuItem>
                                <a href='javascript:void(0);' onClick={()=>{eval(fn)}}>{operate.text}</a>
                            </MenuItem>
                        );
                    }
                });
                const menu = (
                    <Menu>
                        {hiddenOperate}
                    </Menu>
                )
                return(
                    <div>
                        {hiddenOperate.length>0 &&
                        (<Dropdown overlay={menu}>
                            <a className="ant-dropdown-link" href="javascript:void(0);">
                                <Icon type="down" />
                            </a>
                        </Dropdown>)}
                    </div>
                )
            }
        });
        nowWidth += 8; //操作按钮
        if(showCheck) nowWidth += 2; //check框位置
        newColumns = newColumns.map((newColumn) => {
            if(newColumn.hide == "false" && newColumn.oldWidth) {
                newColumn.width = (
                    parseFloat(oldWidthObj[newColumn.dataIndex]) +
                    (100 - nowWidth) * parseFloat(oldWidthObj[newColumn.dataIndex] / nowWidth)
                ) + "%";
                if(useSorter !== false && newColumn.orderkey) {
                    newColumn.sorter = true;
                    if(sortParams && sortParams.length > 0) {
                        sortParams.map(s => {
                            if(s.orderkey == newColumn.orderkey)
                                newColumn.sortOrder = s.sortOrder;
                        });
                    } else {
                        newColumn.sortOrder = false;
                    }
                }
                return newColumn;
            }
            return newColumn;
        });
        return newColumns;
    }
	render() {
		const locale = this.getLocale();
		const { scroll, heightSpace, usePagination, size, useFixedHeader, bordered, showHeader, useFilters, useSorter, noOperate, checkType, useLoading,contentHeight } = this.props;
		const { height, columns, datas, operates, selectedRowKeys, showCheck, loading, sortParams } = this.state;
		const {showCheckedDatas, checkedDatas} = this.state;
        const scrollHeight = scroll ? { scroll: { y: height } } : {};
		const newLoading = useLoading ? { loading: loading } : {};
        let newColumns = this.formatColumns(columns);
		const rowSelection = showCheck ? {
			selectedRowKeys: selectedRowKeys,
            onSelect: (record, selected, selectedRows) => {
                let {selectedRowKeys, checkedDatas = []} = this.state;
                if (isEmpty(selectedRowKeys)) selectedRowKeys = [];
                if (selected) {
                    selectedRowKeys.push(record.randomFieldId);
                    checkedDatas.push(record);
                } else {
                    selectedRowKeys = selectedRowKeys.filter(item => item !== record.randomFieldId)
                    checkedDatas = checkedDatas.filter(item => (item.randomFieldId || item.id) !== record.randomFieldId)
                }
                this.setState({selectedRowKeys, checkedDatas});
                this.props.getSelection && this.props.getSelection(selectedRowKeys, checkedDatas);
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                let {selectedRowKeys, checkedDatas = []} = this.state;
                if (isEmpty(selectedRowKeys)) selectedRowKeys = [];
                if (selected) {
                    selectedRows.forEach(item => selectedRowKeys.push(item.randomFieldId));
                    checkedDatas = checkedDatas.concat(selectedRows);
                } else {
                    selectedRowKeys = selectedRowKeys.filter(item => !changeRows.some(i => item === i.randomFieldId))
                    checkedDatas = checkedDatas.filter(item => !changeRows.some(i => (item.randomFieldId || item.id) === i.randomFieldId))
                }
                this.setState({selectedRowKeys, checkedDatas});
                this.props.getSelection && this.props.getSelection(selectedRowKeys, checkedDatas);
            }
		} : null;
        const checkedRowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange: (sRowKeys, sRows) => {
                this.setState({selectedRowKeys: sRowKeys, checkedDatas: sRows});
                this.props.getSelection && this.props.getSelection(sRowKeys, sRows);
            }
        };
		const paginationConfig = usePagination ? {weaSimple:this.props.weaSimple,pagination:this.getPagination()}:{weaSimple:false,pagination:false}
		return(
			<div className="wea-browser-table table-header-noscroll">
                {showCheck &&
                    <span className="check-button-wrapper">
                        <Button
                            className="check-button"
                            type={showCheckedDatas?'primary':'ghost'}
                            onClick={()=>{this.setState({showCheckedDatas: !showCheckedDatas}), this.props.showCheckedDatasChange(!showCheckedDatas)}}
                        >
                            仅显示已选
                        </Button>
                        {showCheckedDatas && <span className="icon-check-wrapper"><Icon className="icon-check" type="check" /></span>}
                    </span>
                }
                {
                    !showCheckedDatas ?
                    <Table {...scrollHeight}
                    	useFixedHeader={useFixedHeader}
                    	rowSelection={rowSelection}
                    	contentHeight={contentHeight}
                    	columns={newColumns}
    					dataSource={datas}
                    	{...paginationConfig}
                    	checkType={checkType || 'checkbox'}
                    	rowKey={record => record.randomFieldId} // randomFieldId row的标识，和后端协商改数据 和id 一样
                    	onRowClick={this.onRowClick.bind(this)}
                    	onChange={this.onChange.bind(this)}
                    	/>
                    :
                    <Table {...scrollHeight}
                        useFixedHeader={useFixedHeader}
                        rowSelection={checkedRowSelection}
                        contentHeight={contentHeight}
                        columns={newColumns}
                        dataSource={checkedDatas}
                        weaSimple={false}
                        pagination={false}
                        checkType={checkType || 'checkbox'}
                        rowKey={record => record.randomFieldId} // randomFieldId row的标识，和后端协商改数据 和id 一样
                        />
                }
            </div>
		)
	}
	getPagination() {
		//showSizeChanger 默认开启 true
		//showQuickJumper 默认开启 true
		//showTotal 默认开启 true
		const locale = this.getLocale();
		const { showSizeChanger, pageSizeOptions, showQuickJumper, pageinationSize, showTotal} = this.props;
		const { current, count, pageSize } = this.state;
		let obj = {
			defaultCurrent: 1,
			defaultPageSize: pageSize,
			current: current,
			count: count,
			total: count,
			showSizeChanger: showSizeChanger === false ? false : true,
			showQuickJumper: showQuickJumper === false ? false : true,
			pageSizeOptions: pageSizeOptions ? pageSizeOptions : [10, 20, 50, 100],
		};
		if(showTotal !== false) {
			obj.showTotal = total => { return `${locale.total} ${total} ${locale.totalUnit}`; }
		}
		return obj
	}
	getTableDatas(key, clear=true, c, p, s) {
		const { dataKey ,noSkHasPgTable} = this.props;
		// console.log('noSkHasPgTable',noSkHasPgTable);
		const { current, pageSize, sortParams, count } = this.state;
		let newCurrent = c ? c : current;
		if(clear) newCurrent = 1;//页码回到1
		let newPageSize = p ? p : pageSize;
		let newSortParams = s ? s : sortParams;
		let newDataKey = key ? key : dataKey;

		let min = newPageSize * (newCurrent - 1) + 1;
		let max = newPageSize * newCurrent;
		//如需清除状态
		let newClear = clear == false ? clear : true;
		if(newClear) {
			min = 1;
			max = newPageSize;
			newSortParams = [];
			this.setState({ current: 1, pageSize: pageSize, sortParams: [], selectedRowKeys: '' });
		}
		if(typeof this.props.getTableLoading == 'function') this.props.getTableLoading(true);
		if (noSkHasPgTable && noSkHasPgTable.contentType=='hasPgTable') {//没sessionkey有分页的数据
			// console.log('没sessionkey有分页的数据');
			if(c || p){
				// console.log('分页改变调用-->noSkHasPgTable',noSkHasPgTable);
				let newUrl = noSkHasPgTable.url.replace(/&min=(\d)*/g, '').replace(/&max=(\d)*/g, '');
                if (newCurrent > 1 && max > count) max = count;
				newUrl+= '&'+ WeaTools.getFd({min:min,max:max,sortParams: JSON.stringify(newSortParams)})
                this.props.setLoading && this.props.setLoading(true);
                WeaTools.callApi(newUrl,'GET').then(data => {
					this.setState({
						current: newCurrent,
						datas: data.datas,
						columns: data.columns,
						count: data.total,
						sortParams: newSortParams
					})
                    this.props.setLoading && this.props.setLoading(false);
                })
			}else{
				// console.log('初始调用-->noSkHasPgTable',noSkHasPgTable);
				this.setState({
					current:current,
					columns: noSkHasPgTable.hasPgTableData.columns,
					datas: noSkHasPgTable.hasPgTableData.datas,
					count:noSkHasPgTable.hasPgTableData.count,
				})
			}
		}
		if(!noSkHasPgTable && newDataKey) {//有sessionkey有分页的数据
			// console.log('有sessionkey有分页的数据');
			this.props.setLoading && this.props.setLoading(true);
            Promise.all([
				WeaTools.callApi("/api/ec/dev/table/datas",'POST',{ dataKey: newDataKey, min: min, max: max, pageSize:pageSize, sortParams: JSON.stringify(newSortParams)}).then(data => {
					this.setState({
						current: newCurrent,
						datas: data.datas,
						columns: data.columns,
						operates: data.ops,
						showCheck: data.haveCheck,
						sortParams: newSortParams
					});
                    if (data.count) {
                        this.setState({
                            count: data.count,
                        });
                    }
					return data;
				}),
				WeaTools.callApi("/api/ec/dev/table/counts",'POST',{ dataKey: newDataKey }).then(data => {
					this.setState({
						count: data.count,
					});
					if(typeof this.props.onChange == 'function'){
						this.props.onChange({count: data.count, current: newCurrent, pageSize: newPageSize});
					}
					return data;
				})
			]).then(result => {
				const doCheckApi = result[0].haveCheck;
				const ops = result[0].ops;
                this.props.setLoading && this.props.setLoading(false);
				if(doCheckApi || (ops && ops.length>0)){
					const columns = result[0].columns;
					const checkDatas = result[0].datas;
					let newDatas = [];
					checkDatas.map(d => {
						let newData = {};
						columns.map(c => {
							if((c.from && c.from === 'set') || c.dataIndex === 'randomFieldId')
								newData[c.dataIndex] = d[c.dataIndex];
						})
						newDatas.push(newData);
					})
					WeaTools.callApi("/api/ec/dev/table/checks",'POST',{ randomDatas: JSON.stringify(newDatas), dataKey: dataKey }).then(data => {
						let datas = this.state.datas;
						let nDatas = data.datas;
						datas = datas.map(d => {
							let newN = cloneDeep(d);
							nDatas.map(n => {
								if(n.randomFieldId == d.randomFieldId) {
									for(let p in n) {
										newN[p] = n[p];
									}
								}
							})
							return newN
						})
						this.setState({ datas: datas });
						if(typeof this.props.getTableLoading == 'function') this.props.getTableLoading(false);
					});
				}
			});
		}
	}
	onChange(pagination, filters, sorter) {
		let params = {
			current: pagination.current,
			pageSize: pagination.pageSize,
			sortParams: sorter.column ? [{ orderkey: sorter.column.orderkey, sortOrder: sorter.order }] : []
		}
		// this.setState(params)
		this.getTableDatas('', false, params.current, params.pageSize, params.sortParams);
	}
	onRowClick(record, index) {
		if(typeof this.props.onRowClick == 'function')
			this.props.onRowClick(record, index);
	}
	getColumns(columns) {
		let newColumns = cloneDeep(columns);
		return newColumns && newColumns.map((column) => {
			let newColumn = column;
			newColumn.render = (text, record, index) => { //前端元素转义
				let valueSpan = record[newColumn.dataIndex + "span"] || record[newColumn.dataIndex];
                // let valueSpan = record[newColumn.dataIndex + "span"];
				function createMarkup() { return { __html: valueSpan }; };
				return(
					<div className="wea-url" dangerouslySetInnerHTML={createMarkup()} />
				);
			}
			// console.log('newColumns',newColumns)
			return newColumn;
		});
	}
}


export default Main;